﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YAMP;

namespace SayisalAnaliz.Library
{
    public static class NewtonRaphsonYontemi
    {

        public static double[] Uygula(double baslangic, double epsilon, string fonksiyon)
        {
            fonksiyon = fonksiyon.Replace(',', '.');
            double x0 = baslangic;
            double fx0 = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = x0 })).Value;
            double a = x0 - epsilon;
            double b = x0 + epsilon;
            double fa = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = a })).Value;
            double fb = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = b })).Value;
            double fx0_turev = (fb - fa) / (2 * epsilon);

            double x1 = x0 - (fx0 / fx0_turev);
            double x2;
            do
            {
                double fx1 = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = x1 })).Value;
                a = x1 - epsilon;
                b = x1 + epsilon;
                fa = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = a })).Value;
                fb = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = b })).Value;
                double fx1_turev = (fb - fa) / (2 * epsilon);
                x2 = x1 - (fx1 / fx1_turev);
                x0 = x1;
                x1 = x2;               

            } while (Math.Abs(x2 - x0) > epsilon);
            double[] sonuclar = new double[2];
            sonuclar[0] = x2;
            sonuclar[1] = ((ScalarValue)Parser.Parse(fonksiyon).Execute(new { x = x2 })).Value;
            return sonuclar;
        }
    }
}
